package com.core.platform;

import com.core.log.ActionLog;
import com.core.log.ActionLoggerImpl;
import com.core.util.CharacterEncodings;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class PlatformFilter implements Filter {
    private final Logger logger = LoggerFactory.getLogger(PlatformFilter.class);

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        if (request instanceof HttpServletRequest && response instanceof HttpServletResponse) {
            filter((HttpServletRequest) request, (HttpServletResponse) response, chain);
        } else {
            chain.doFilter(request, response);
        }
    }

    private void filter(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
        request.setCharacterEncoding(CharacterEncodings.UTF_8);
        ActionLoggerImpl actionLogger = ActionLoggerImpl.get();
        try {
            actionLogger.initialize();

            chain.doFilter(request, response);
        } finally {
            logResponse(response, request);
            logger.debug("=== finish request processing ===");
            actionLogger.save();
        }
    }

    private void logResponse(HttpServletResponse response, HttpServletRequest request) {
        int status = response.getStatus();
        logger.debug("responseHTTPStatus={}", status);
        logHeaders(response);
        ActionLog actionLog = ActionLoggerImpl.get().currentActionLog();
        actionLog.setHTTPStatusCode(status);
        if (!StringUtils.hasText(actionLog.getRequestURI())) {
            actionLog.setRequestURI(request.getRequestURI());
        }
    }

    private void logHeaders(HttpServletResponse response) {
        for (String name : response.getHeaderNames()) {
            logger.debug("[response-header] {}={}", name, response.getHeader(name));
        }
    }

    @Override
    public void destroy() {
    }
}

